#if UNITY_EDITOR_WIN

using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using BF;
using SFB;

public class ProtobufGenerateEditor : EditorWindow
{
    public string proto_file;
    public string csharp_out;

    [MenuItem("Tools/Protobuf-Generate")]
    static void Init()
    {
        ProtobufGenerateEditor window = EditorWindow.GetWindow<ProtobufGenerateEditor>();
        window.Show();
    }

    private void OnGUI()
    {
        GUILayout.BeginVertical();

        proto_file = EditorGUILayout.TextField("proto_file", proto_file);
        if (GUILayout.Button("Choose proto_file"))
        {
            ChooseOriFilePath();
        }
        csharp_out = EditorGUILayout.TextField("csharp_out", csharp_out);
        if (GUILayout.Button("Choose csharp_out"))
        {
            ChooseOutDir();
        }

        if (GUILayout.Button("Generate"))
        {
            PrepareGenerate();
        }
        GUILayout.EndVertical();
    }

    private void ChooseOriFilePath()
    {
        string[] paths = StandaloneFileBrowser.OpenFilePanel("OriginCSFile", Application.dataPath, "proto", false);
        if (paths.Length > 0)
        {
            proto_file = paths[0];
        }
    }

    private void ChooseOutDir()
    {
        string[] paths = StandaloneFileBrowser.OpenFolderPanel("OriginOutDir", Application.dataPath, false);
        if (paths.Length > 0)
        {
            csharp_out = paths[0];
        }
    }

    private void PrepareGenerate()
    {
        if (string.IsNullOrEmpty(proto_file))
        {
            Debug.LogError("proto_file is empty");
        }
        else if (!File.Exists(proto_file))
        {
            Debug.LogError($"file: {proto_file} is not exist");
        }
        else if (string.IsNullOrEmpty(csharp_out))
        {
            Debug.LogError("csharp_out is empty");
        }
        else if (!Directory.Exists(csharp_out))
        {
            Debug.LogError($"directory: {csharp_out} is not exist");
        }
        else
        {
            Generate();
        }
    }

    private void Generate()
    {
        string protogen_exe = Application.dataPath + "/Plugins/ThirdPlugin/Protobuf/protogen.exe";
        string proto_path = Path.GetDirectoryName(proto_file);
        string proto_file_name = Path.GetFileName(proto_file);
        string cmd_arguments = $"--proto_path={proto_path} --csharp_out={csharp_out} {proto_file_name}";

        Debug.Log($"[Protobuf] Generate Start");
        Debug.Log($"{protogen_exe} {cmd_arguments}");

        CommandUtil.Result result = CommandUtil.Execute(protogen_exe, cmd_arguments);

        if (string.IsNullOrEmpty(result.error))
        {
            Debug.Log($"[Protobuf] Generate Success");
        }
        else
        {
            Debug.LogError($"[Protobuf] Generate Error: {result.error}");
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}

#endif